import api from '../../api/index'
import CONFIG from '../../utils/config'
const app = getApp()

const defaultText = {
    getUserInfo: {
        title: '获取您的用户信息',
        content: '我们需要获取您的用户信息，以便用于之后的操作'
    },
    getPhoneNumber: {
        title: '获取您的手机号码',
        content: '我们需要获取您的手机号码，以便用于之后的操作'
    },
    openSetting: {
        title: '获取您的打开设置',
        content: '点击确定后将会打开您的权限配置'
    },
}

const getSetting = () => {
    return new Promise((resolve, reject) => {
        wx.getSetting({
            success: res => {
                console.log(res)
                if (res.errMsg === 'getSetting:ok') {
                    resolve(res.authSetting)
                } else {
                    reject(res)
                }
            }
        })
    })
}

const getUserInfo = () => {
    return new Promise((resolve, reject) => {
        wx.getUserInfo({
            lang: 'zh_CN',
            success: res => {
                resolve(res)
            }
        })
    })
}

Component({
    properties: {
        show: {
            type: Boolean,
            value: false
        }
    },
    options: {
        addGlobalClass: false
    },
    externalClasses: ['lk-class'],
    data: {
        type: 'getUserInfo',
        title: '',
        content: '',
        mask: true,
        cancelBtn: true
    },
    methods: {
        /**
         * 打开模态框
         * @param {Boolean} options.mask @default true -是否允许点击浮层后关闭
         * @param {String} options.openType @default '' -授权类型
         * @param {String} options.title @default '' -弹出层标题
         * @param {String} options.content @default '' -提示内容
         * @param {Boolean} options.cancelBtn @default true -是否显示取消按钮
         * @param {Function} options.success  -授权成功后回调函数
         * @param {Function} options.cancel  -失败后回调
         * @param {Function} options.error  -出现错误
         * */
        async show(options = {}) {
            let type = options.openType || 'getUserInfo'
            let modalMask = true
            let cancelBtn = true
            let titleText = ''
            let contentText = ''

            titleText = options.title || defaultText[type].title
            contentText = options.content || defaultText[type].content
            options.cancelBtn !== undefined ? cancelBtn = options.cancelBtn : null
            options.mask !== undefined ? modalMask = options.mask : null
            options.success && typeof options.success === 'function' ? this.success = options.success : null
            options.cancel && typeof options.cancel === 'function' ? this.cancel = options.cancel : null
            options.error && typeof options.error === 'function' ? this.error = options.error : null

            // 判断是否已经在服务端存入了用户昵称
            const userInfo = wx.getStorageSync('userInfo')
            if (!options || !options.must) {
                if (type === 'getUserInfo') {
                    if (userInfo.wechatimg && userInfo.nickname && userInfo.gender) {
                        if (userInfo.gender !== "" && userInfo.gender !== " " && userInfo.wechatimg !== "" && userInfo.nickname !== "") {
                            this.success(userInfo)
                            return
                        }
                    }
                }
                if (type === 'getPhoneNumber') {
                    if (userInfo.mobile) {
                        this.success()
                        return
                    }
                }
            }

            // 判断是否已经授权
            if (type === 'getUserInfo') {
                try {
                    const s = await getSetting()
                    if (s['scope.userInfo']) {
                        const info = await getUserInfo()
                        console.log(info)
                        this.getUserInfo(info)
                        return
                    }
                } catch (e) {
                    console.error('判断是否已经授权失败', e)
                }
            }

            this.setData({
                show: true,
                cancelBtn,
                type,
                mask: modalMask,
                title: titleText,
                content: contentText
            })
        },
        hide() {
            this.setData({
                show: false
            })
        },
        success() {
        },
        cancel() {
        },
        error() {
        },
        handlerClose() {
            this.setData({
                show: false
            })
            this.cancel()
        },
        handlerError(e) {
            this.error(e)
        },
        handlerMaskCloseModal() {
            if (this.data.mask) {
                return
            }
            this.setData({
                show: false
            })
            this.cancel()
        },
        handlerOpenSetting(e){
            this.setData({
                show: false
            })
            this.success(e)
        },
        async handlerUserInfo(e) {
            const {detail} = e
            this.getUserInfo(detail)
        },
        async getUserInfo(detail) {
            const {errMsg} = detail
            if (errMsg === 'getUserInfo:ok') {
                this.setData({
                    show: false
                })
                console.log(detail);
                this.success(detail.userInfo)
                this.saveUserInfo(detail)
            } else {
                this.cancel()
                this.error(detail)
            }
        },
        async handlerPhone(e) {
            const {detail} = e
            const {errMsg} = detail
            if (errMsg === 'getPhoneNumber:ok') {
                this.setData({
                    show: false
                })
                this.success(detail, e)
                this.savePhone(detail)
            } else {
                this.cancel()
                this.error(detail, e)
            }
        },
        saveUserInfo(options) {
            let userInfo = wx.getStorageSync('userInfo');
            userInfo.gender = options.userInfo.gender == 0 ? 2 : 1
            userInfo.nickname = options.userInfo.nickName
            userInfo.wechatimg = options.userInfo.avatarUrl
            console.log(userInfo);
            wx.setStorageSync('userInfo', userInfo)
            const data = {
                nickname: options.userInfo.nickName,
                wechatimg: options.userInfo.avatarUrl,
                gender: options.userInfo.gender == 0 ? 2 : 1
            }
            console.log('授权调动保存用户信息方法', options)
            api.post('/api/user/savenickname', {data}).then(res => {
                app.getHttpUser()
            }).catch(e => {
                wx.showToast({
                    icon: 'none',
                    title: '保存用户信息失败'
                })
                console.error(e)
            })
        },
        savePhone(options) {
            const data = {
                encrypteddata: options.encryptedData,
                iv: options.iv,
            }
            api.post(`/api/user/savewamobile/${CONFIG.orgCode}/${CONFIG.appCode}`, {data}).then(res => {
                app.getHttpUser()
            }).catch(e => {
                wx.showToast({
                    icon: 'none',
                    title: '用户手机号码绑定失败'
                })
                console.error(e)
            })
        }
    }
})
